﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ControllerClient
{
    public class FileServer
    {
        private static readonly string CLASS_NAME = "FileServer";

        public delegate void FileChangeEventHandler(String cmdfilename);

        public static event FileServer.FileChangeEventHandler FileChangEvent;

        private static bool StopMonitor = false;

        private static Thread monitorEventThread;

        private static  string CMDFILE_PATH ="";//命令文件路径
      //  private static readonly string CMDFILE_PATH = "\\EPMS\\";//命令文件路径

        public FileServer(String path)
        {
            CMDFILE_PATH = path;
        }
        private static void MonitorEvent()
        {
          //  Debug.WriteLine("文件检查服务已启动。。。");
            while (!StopMonitor)
            {
                Thread.Sleep(1000);
                try
                {
                   String[] cmdfiles= Directory.GetFiles(@CMDFILE_PATH);
                   if (cmdfiles.Length > 0)
                   {
                       for (int i = 0; i < cmdfiles.Length; i++)
                       {
                          // Debug.WriteLine(cmdfiles[i]);
                           if (cmdfiles[i].EndsWith(".txt")|| cmdfiles[i].EndsWith("set.conf"))
                           {
                               if (FileServer.FileChangEvent != null)
                               {
                                       Thread.Sleep(500);//延迟等待文件传输完成
                                       FileServer.FileChangEvent(cmdfiles[i]);
                               }
                           }
                       }
                   }
                }
                catch (Exception e1)
                {
                      Debug.WriteLine(e1.StackTrace);
                }
                

            }
        }

        public static void StartListener(String path)
        {
            CMDFILE_PATH = path;
            FileServer.monitorEventThread = new Thread(new ThreadStart(FileServer.MonitorEvent));
            FileServer.monitorEventThread.IsBackground = (true);
            FileServer.monitorEventThread.Start();
        }
        public static void StopListener()
        {
            FileServer.StopMonitor = true;
            if (FileServer.monitorEventThread != null)
            {
                FileServer.monitorEventThread.Abort();
            }

            FileServer.FileChangEvent = null;
        }

    }
}
